﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Gfw.BLL.Basic.User;
using Gfw.Models.Admin;
using Gfw.Web.Common;
using Gfw.Web.Models.User;
using Gfw.Web.Models.Users;
using Gfw.BLL.Basic.Account;
using Gfw.Web.Models.Account;
using Gfw.Infrastructure.ExceptionImpl;

namespace Gfw.Web.Controllers
{
  /// <summary>
  /// 
  /// </summary>
    public class UserController : Controller
    {
        #region 用户基本信息
        [LAuthorize]
        public ActionResult IndexPartial()
        {
            return PartialView();
        }
        #endregion

        #region 用户登录

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
          
            //  UserGenealogyLogic.GetFamily("sfsdf");
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }


        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(UserLoginModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (Session["ValidateCode"].ToString() != model.VerifyCode)
                        throw new Exception("验证码不正确。");
                    if (L.Manage.Authentication.Login(model.UserName, EncryptAlgorithmHelper.Encrypt(model.Password, model.UserName)))
                    {
                       
                     //   FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Default");
                        }
                    }

                    throw new Exception("用户名或者密码错误或者无权限");

                }
            }
            catch (Exception exp)
            {
                ModelState.AddModelError("", exp.Message);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        #endregion

        #region 用户注册

        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        [LAuthorize]
        public ActionResult Register(long cn)
        {
            UserRegisterModel current = null;
            UserRegisterModel parent = null;
            UserAccountSummaryModel account = null;
            try
            {
                parent =
                   UserLogic.CheckParent(L.Manage.Authentication.Context.CurrentUser.Code, cn);
                account = UserAccountLogic.GetUserAccountSummary(L.Manage.Authentication.Context.CurrentUser.Id);
            }
            catch
            {
            }

            if (parent != null)
            {
                current = new UserRegisterModel()
                              {
                                  Parentid = parent.Id,
                                  CodeNumber = cn,
                                  ParentName = parent.LoginName,
                                  
                                  Balance = account == null ? 0 : account.ElectronicMoney,
                              };
            }
            return View(current);
        }

        [PauseService(Order = 0)]
        [SecurityVerify(Order = 1)]
        [LAuthorize]
        [HttpPost]
        public ActionResult Register(UserRegisterModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    model.LoginName = model.LoginName.Trim(); // 去空白
                    model.Recommender = L.Manage.Authentication.Context.CurrentUser.Id;
                    model.RecommenderName =
                        (L.Manage.Authentication.Context.CurrentUser.Tag as UsrUser).LoginName;
                    model.Code = Convert.ToString(model.CodeNumber, 2);
                    model.ParentArea = Convert.ToInt32(Convert.ToString(model.CodeNumber, 2).Last().ToString(CultureInfo.InvariantCulture));


                    // 注册立即转账，防止用户恶意注册
                    TransferModel transfer = new TransferModel()
                    {
                        Balance = model.Balance,
                        Count = 560,
                        ToUser = model.LoginName,
                    };


                    if (L.Manage.Authentication.Context.CurrentUser.LoginName == transfer.ToUser)
                        throw new GfwVerifyException("转入用户不能是当前用户！");
                    if (transfer.Balance < 560)
                        throw new GfwVerifyException("D币金额小于560");

                    if (!UserLogic.Register(model))
                    {
                        ModelState.AddModelError("", "注册失败！");
                        return View(model);
                    }
                    else // 注册成功！立即转账560
                    {
                        UserAccountLogic.Transfer(L.Manage.Authentication.Context.CurrentUser.Id, transfer);
                    }

                    return RedirectToAction("Index1", "UserGenealogy", new { type = "goback" });
                }
                catch (Exception exp)
                {
                    ModelState.AddModelError("", exp.Message);
                }
            }
            return View(model);
        }

        //[LAuthorize]
        //public ActionResult Register(string code)
        //{

        //    UserRegisterModel model = new UserRegisterModel()
        //    {
        //        ParentId = parentId,
        //        ParentArea = parentArea,

        //    };
        //    return View(model);
        //}
        //[LAuthorize]
        //[HttpPost]
        //public ActionResult Register(string parentId, bool parentArea, UserRegisterModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        try
        //        {
        //            model.Recommender = L.Manage.Authentication.Context.CurrentUser.Id;
        //            model.Code = L.Manage.Authentication.Context.CurrentUser.Code;
        //            UserLogic.Register(model);
        //            return RedirectToAction("Index", "Default");
        //        }
        //        catch (Exception exp)
        //        {
        //            ModelState.AddModelError("", exp.Message);
        //        }
        //    }
        //    return View(model);
        //}

        #endregion

        #region 用户资料

        /// <summary>
        /// 修改用户个人信息
        /// </summary>
        /// <returns></returns>
        [SecurityVerify]
        [LAuthorize]
        public ActionResult ChangeUserBasicInfo()
        {
            try
            {
                string loginName = L.Manage.Authentication.Context.CurrentUser.LoginName;
                if (!string.IsNullOrEmpty(loginName))
                {
                    UserBasicInfoModel model = UserLogic.GetUserBasicInfo(loginName);
                    if (model == null)
                        return HttpNotFound();

                    return View(model);
                }
                else
                    return HttpNotFound();
            }
            catch (System.Exception ex)
            {
                return HttpNotFound(ex.Message);
            }
        }

        /// <summary>
        /// 修改用户个人信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [SecurityVerify]
        [LAuthorize]
        [HttpPost]
        public ActionResult ChangeUserBasicInfo(UserBasicInfoModel model)
        {
            try
            {
                UserLogic.EditUserBasicInfo(model);
                return View(model);
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(model);
            }
        }


        /// <summary>
        /// 修改用户绑定信息
        /// </summary>
        /// <returns></returns>
        [SecurityVerify]
        [LAuthorize]
        public ActionResult ChangeUserBindingInfo()
        {
            try
            {
                // 网页已过期!只适用于IE
                Response.Expires = 0;
                Response.Buffer = true;
                Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
                Response.AddHeader("pragma", "no-cache");
                Response.CacheControl = "no-cache";


                string loginName = L.Manage.Authentication.Context.CurrentUser.LoginName;
                if (!string.IsNullOrEmpty(loginName))
                {
                    UserBindingInfoModel model = UserLogic.GetUserBindingInfo(loginName);
                    if (model == null)
                        return HttpNotFound();

                    var bankList = new UserBankListModel();
                    ViewBag.BankList = new SelectList(bankList.ToList<string>());


                    return View(ShowStarUserBindingInfoModel(model));
                }
                else
                    return HttpNotFound();
            }
            catch (System.Exception ex)
            {
                return HttpNotFound(ex.Message);
            }
        }

        /// <summary>
        /// 转换成*号显示绑定信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private UserBindingInfoModel ShowStarUserBindingInfoModel(UserBindingInfoModel model)
        {
            if (!string.IsNullOrWhiteSpace(model.IDCard))
                model.ShowIDCard = model.IDCard.Substring(0, 6) + "***" + model.IDCard.Substring(model.IDCard.Length - 4);

            if (!string.IsNullOrWhiteSpace(model.BankCardNo) && model.BankCardNo.Length > 12)
                model.ShowBankCardNo = model.BankCardNo.Substring(0, 8) + "***" + model.BankCardNo.Substring(12);
            else if (!string.IsNullOrWhiteSpace(model.BankCardNo))
                model.ShowBankCardNo = model.BankCardNo.Substring(0, 1) + "***";

            if (!string.IsNullOrWhiteSpace(model.BankUserName))
                model.ShowBankUserName = model.BankUserName.Substring(0, 1) + "***";

            if (!string.IsNullOrWhiteSpace(model.BankAddress))
                model.ShowBankAddress = model.BankAddress.Substring(0, 1) + "***";

            if (!string.IsNullOrWhiteSpace(model.Tenpay) && model.Tenpay.Length > 3)
                model.ShowTenpay = "***" + model.Tenpay.Substring(3);
            else if (!string.IsNullOrWhiteSpace(model.Tenpay))
                model.ShowTenpay = model.Tenpay.Substring(0, 1) + "***";

            if (!string.IsNullOrWhiteSpace(model.Alipay) && model.Alipay.Length > 3)
                model.ShowAlipay = "***" + model.Alipay.Substring(3);
            else if (!string.IsNullOrWhiteSpace(model.Alipay))
                model.ShowAlipay = model.Alipay.Substring(0, 1) + "***";

            return model;
        }

        /// <summary>
        /// 修改用户绑定信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [SecurityVerify]
        [LAuthorize]
        [HttpPost]
        public ActionResult ChangeUserBindingInfo(UserBindingInfoModel model)
        {
            var bankList = new UserBankListModel();
            ViewBag.BankList = new SelectList(bankList.ToList<string>());

            try
            {
                if (!UserLogic.CheckUserIDCard(L.Manage.Authentication.Context.CurrentUser.LoginName,
                    model.IDCard))
                {
                    model.IDCard = string.Empty;
                    throw new Gfw.Infrastructure.ExceptionImpl.GfwVerifyException("该身份证号已注册，不能使用！");
                }

                if (string.IsNullOrWhiteSpace(model.BankUserName))
                    throw new Gfw.Infrastructure.ExceptionImpl.GfwVerifyException("请填写开户名！");

                UserLogic.EditUserBindingInfo(model);
                UserLogic.EditUserFinanceInfo(model);

                //return RedirectToAction("CsqResult");
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }

            return View(ShowStarUserBindingInfoModel(model));
        }

        #endregion

        #region 登录密码

        /// <summary>
        /// 修改用户登录密码
        /// </summary>
        /// <returns></returns>
        [SecurityVerify]
        [LAuthorize]
        public ActionResult ChangeLoginPassword()
        {
            try
            {
                string loginName = L.Manage.Authentication.Context.CurrentUser.LoginName;
                if (!string.IsNullOrEmpty(loginName))
                {
                    return View(new UserLoginPasswordModel()
                        {
                            LoginName = loginName,
                        });
                }
                else
                    return HttpNotFound();
            }
            catch (System.Exception ex)
            {
                return HttpNotFound(ex.Message);
            }
        }

        [SecurityVerify]
        [LAuthorize]
        [HttpPost]
        public ActionResult ChangeLoginPassword(UserLoginPasswordModel model)
        {
            try
            {
                ViewBag.Done = UserLogic.ChangeLoginPassword(model);

                return View(new UserLoginPasswordModel()
                {
                    LoginName = model.LoginName,
                });
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View();
            }
        }

        #endregion

        #region 二级密码

        /// <summary>
        /// 修改用户二级密码
        /// </summary>
        /// <returns></returns>
        [LAuthorize]
        public ActionResult ChangeSecondPassword()
        {
            try
            {
                string loginName = L.Manage.Authentication.Context.CurrentUser.LoginName;
                if (!string.IsNullOrEmpty(loginName))
                {
                    ViewBag.IsFirst = UserLogic.IsFirstSetSecondPassword(loginName);
                    return View(new UserSecondPasswordModel()
                        {
                            LoginName = loginName,
                        });
                }
                else
                    return HttpNotFound();
            }
            catch (System.Exception ex)
            {
                return HttpNotFound(ex.Message);
            }
        }

        [LAuthorize]
        [HttpPost]
        public ActionResult ChangeSecondPassword(UserSecondPasswordModel model)
        {
            try
            {
                ViewBag.Done = UserLogic.ChangeSecondPassword(model);
                ViewBag.IsFirst = UserLogic.IsFirstSetSecondPassword(model.LoginName);

                return View(new UserSecondPasswordModel()
                {
                    LoginName = model.LoginName,
                });
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View();
            }
        }

        #endregion

        #region 二级密保验证

        [LAuthorize]
        public ActionResult Security(string ReturnUrl)
        {
            return View();
        }

        [LAuthorize]
        [HttpPost]
        public ActionResult Security(UserSecondSecurityModel model, string ReturnUrl)
        {
            // 验证二级密码
            if (UserLogic.CheckSecondSecurity(L.Manage.Authentication.Context.CurrentUser.LoginName,
                EncryptAlgorithmHelper.Encrypt(model.Password2, L.Manage.Authentication.Context.CurrentUser.LoginName)))
            {
                Params.SecondVerifyTimeOut = DateTime.Now.AddSeconds(60);
                Params.SecondVerify = true;
                return new RedirectResult(ReturnUrl);
            }
            ModelState.AddModelError("", "二级密码错误！");
            return View();
            
        }
        #endregion

        #region 密保问题

        /// <summary>
        /// 修改密保问题
        /// </summary>
        /// <returns></returns>
        [SecurityVerify]
        [LAuthorize]
        public ActionResult ChangeSecurityQuestion()
        {
            try
            {
                string loginName = L.Manage.Authentication.Context.CurrentUser.LoginName;
                if (!string.IsNullOrEmpty(loginName))
                {
                    UserSecurityQuestionModel model = UserLogic.GetSecurityQuestions(loginName);
                    if (model == null)
                        return HttpNotFound();

                    var questionList = new UserQuestionListModel();
                    ViewBag.QuestionList = new SelectList(questionList.ToList<string>());

                    bool isFirst = string.IsNullOrWhiteSpace(model.Answer1) &&
                        string.IsNullOrWhiteSpace(model.Answer2) &&
                        string.IsNullOrWhiteSpace(model.Answer3); // 是否第一次运行密保问题

                    ViewBag.isFirst = isFirst;


                    if (!isFirst) // 不是第一次运行，则显示为*
                    {
                        model.Answer1 = model.Answer1.Substring(0, 1) + "***";
                        model.Answer2 = model.Answer2.Substring(0, 1) + "***";
                        model.Answer3 = model.Answer3.Substring(0, 1) + "***";
                    }

                    return View(model);
                }
                else
                    return HttpNotFound();
            }
            catch (System.Exception ex)
            {
                return HttpNotFound(ex.Message);
            }
        }

        [SecurityVerify]
        [LAuthorize]
        [HttpPost]
        public ActionResult ChangeSecurityQuestion(UserSecurityQuestionModel model)
        {
            ViewBag.isFirst = true;
            var questionList = new UserQuestionListModel();
            ViewBag.QuestionList = new SelectList(questionList.ToList<string>());

            try
            {
                if (string.IsNullOrWhiteSpace(model.Answer1) ||
                        string.IsNullOrWhiteSpace(model.Answer2) ||
                        string.IsNullOrWhiteSpace(model.Answer3))
                {
                    ModelState.AddModelError("", "请填写密保问题，注意：保存后不可修改！");
                    return View(model);
                }

                UserLogic.EditSecurityQuestion(model);
                return RedirectToAction("CsqResult");
            }
            catch (System.Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(model);
            }
        }

        [LAuthorize]
        public ActionResult CsqResult()
        {
            return View();
        }

        #endregion
    }
}
